package org.mclll.xwangplugin.town.command.executor;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import org.bukkit.entity.Player;
import org.mclll.xwangplugin.town.database.domain.TownDO;
import org.mclll.xwangplugin.town.database.domain.TownPlayerDO;
import org.mclll.xwangplugin.town.database.mapper.manage.TownManage;
import org.mclll.xwangplugin.town.database.mapper.manage.TownPlayerManage;
import org.mclll.xwangplugin.town.enums.PlayerTownIdentity;
import org.mclll.xwangplugin.town.lp.LuckPermsTown;

import java.util.Collections;

import static org.mclll.xwangplugin.town.config.TownContext.*;

public class TownLeaveExecutor {
    public static void leave(Player player, String[] args) {
        TownPlayerDO townPlayer = TownPlayerManage.selectByUuid(player.getUniqueId().toString());
        if (townPlayer.getIdentity() == PlayerTownIdentity.GENSHIN) {
            player.sendMessage(NO_HAVE_TOWN);
            return;
        }
        if (townPlayer.getIdentity() == PlayerTownIdentity.LEADER) {
            player.sendMessage(LEADER_CANT_LEAVE);
            return;
        }
        TownDO town = TownManage.selectByUuid(townPlayer.getTownUuid());
        if (args == null || args.length == 0 || !"confirm".equals(args[1])) {
            player.sendMessage(
                    Component.text(String.format(LEAVE_TOWN_CONFIRM, town.getName()))
                            .append(Component.text(CONFIRM_BUTTON).clickEvent(ClickEvent.runCommand("/poitown leave confirm")).hoverEvent(HoverEvent.showText(Component.text(CONFIRM_BUTTON))))
                            .append(Component.text("         "))
                            .append(Component.text(CANCEL_BUTTON).hoverEvent(HoverEvent.showText(Component.text(CANCEL_BUTTON))))

            );
            return;
        }
        TownPlayerDO updateParam = new TownPlayerDO();
        updateParam.setUuid(town.getUuid());
        updateParam.setIdentity(PlayerTownIdentity.GENSHIN);
        updateParam.setTownUuid("");
        TownPlayerManage.updateByUuid(updateParam);
        LuckPermsTown.kickPlayerFromTown(Collections.singletonList(townPlayer.getName()));
    }
}
